package com.CmJava.utils;

import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class DownUtil {
    public static void downFileOutsideJar(HttpServletResponse response, File file) {
        BufferedInputStream bufferedInputStream = null;
        ServletOutputStream servletOutputStream = null;

        try {

            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));

            byte[] bytes = new byte[bufferedInputStream.available()];
            bufferedInputStream.read(bytes);

            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            servletOutputStream = response.getOutputStream();
            servletOutputStream.write(bytes);
            servletOutputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }

                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void downFileInsideJar(HttpServletResponse response) {
        InputStream inputStream=null;
        ServletOutputStream servletOutputStream=null;
        try {
            //由于SpringBoot打包成jar，里面文件结构都会变，用相对路径会在部署后出问题
            //可以用该类去读取
            ClassPathResource classPathResource = new ClassPathResource("static/downFile/BlockVs.zip");

            inputStream = classPathResource.getInputStream();

            byte[] bytes = new byte[inputStream.available()];

            inputStream.read(bytes);

            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("俄罗斯方块对战版.zip", "UTF-8"));

            servletOutputStream = response.getOutputStream();
            servletOutputStream.write(bytes);
            servletOutputStream.flush();


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (inputStream!=null) {
                    inputStream.close();
                }

                if (servletOutputStream!=null) {
                    servletOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
